package com.dongdongshop.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    //创建shiro过滤器链工厂类
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager) {
        //创建shiro过滤器工厂bean
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();

        //设置安全管理器
        factoryBean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro过滤器
        /*
         * 不需要登录 直接放过 anon
         * 必须登录才能访问 authc
         * 登录也不行，必须有权限才能访问 perms[ad]
         *退出登录 logout
         * */
        Map<String, String> map = new LinkedHashMap<>();

//        map.put("/logout","logout");
        map.put("/index","authc");
//        map.put("/loginRegister/**","anon");
//        map.put("/js/**","anon");
//        map.put("/**", "authc");

//        factoryBean.setLoginUrl("/index");
        factoryBean.setLoginUrl("/toLogin");
        factoryBean.setUnauthorizedUrl("/unauthorized");
        factoryBean.setFilterChainDefinitionMap(map);

        return factoryBean;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm loginReaml) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//        关联reaml 我们自己写的登录和授权的逻辑类
        defaultWebSecurityManager.setRealm(loginReaml);
        return defaultWebSecurityManager;
    }

    @Bean
    public LoginRealm loginReaml(@Autowired  HashedCredentialsMatcher hashedCredentialsMatcher) {
        LoginRealm loginReaml = new LoginRealm();
        //开启密码加密
        loginReaml.setCredentialsMatcher(hashedCredentialsMatcher);
        return loginReaml;
    }

    //    开启密文加密
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //指定加密方式
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        //加密的次数
        hashedCredentialsMatcher.setHashIterations(3);
        //设置编码
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);

        return hashedCredentialsMatcher;
    }
}